<?php
namespace My\Controller;

use Utuo\BackgroundController;

class CustomerProductController extends BackgroundController {
	
	public function _initialize() {
		$this->setControllerTitle('商城信息');
		$this->setActionTitle(array(
				'index' => '商城信息',
				'wechat' => '微信回复设置',
				'url' => '商城地址',
		));
		$this->setActionNav('index,wechat,url');
	}
	
	// 商城信息
	public function indexAction() {
		// 合作商分店设置
		$dProduct = D('CustomerProduct');
		$customerProduct = $dProduct->find($this->aid);
		if (!$customerProduct) {
			$data = array(
					'id' => $this->aid,
					'cid' => $this->aid,
			);
			if (!$dProduct->add($data)) {
				$this->error('添加商城信息失败');
			}
			$customerProduct = $dProduct->find($this->aid);
		}
		// 合作商商城设置
		$pid = session("pid");
		$partnerProduct = M("PartnerProduct")->find($pid);
		$customerProduct['name'] = $partnerProduct['name'];
		$customerProduct['tel'] = $partnerProduct['tel'];
		$this->assign("customerProduct", $partnerProduct);
		$this->display();
	}
	
	// 微信回复设置
	public function wechatAction() {
		$wechat_rule = '__customer_product_rule__';
		$d = D('WechatReply');
		$reply = $d->getReply($this->aid, $wechat_rule);
		if ( !$reply ) {
			$url = url('Home', 'Shop', 'index', 'sid=' . $this->aid, true);
			$id = $d->setKeywordReply($this->aid, $wechat_rule, '合作商商城', '合作商商城', '点击进入【合作商商城】', '', $url);
			$id && $reply = $d->find($id);
		}
		$reply['keyword'] = trim($reply['keyword'], ' ,');
		$this->assign('reply', $reply);
		$this->display();
	}
	
	// 提交微信回复
	public function wechatPostAction() {
		$d = D('WechatReply');
		if ($d->create()) {
			$d->keyword = $d->parseKeyword($d->keyword);
			if ($d->save()) {
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError();
	}
	
	public function urlAction() {
		$customerProduct = M('CustomerProduct')->find($this->aid);
		$customerProduct['url'] = url('Home', 'Shop', 'index', "sid={$this->aid}", true);
		$this->assign('customerProduct', $customerProduct);
		$this->display();
	}
}